package com.summer.service.job;

import com.summer.entity.UserHulu;
import com.summer.mapper.UserHuluDAO;
import com.summer.service.thirdpart.IHuLuService;
import com.summer.util.Constant;
import com.summer.util.ServiceResult;
import com.summer.util.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
public class TimingJob {

    @Value("${system.prefix}")
    private String PREFIX;
    @Resource
    private UserHuluDAO userHuluDAO;
    @Resource
    private IHuLuService huLuService;

    /**
     * 拉取葫芦报告
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 */2 * * * ? ")
    public void getHuluReport(){
        boolean getLock = false;
        try {
            //todo 若任务执行时间过短，则有可能在等锁的过程中2个服务任务都会获取到锁，这与实际需要的功能不一致，故需要将waitTime设置为0
            if (getLock = RedissLockUtil.tryLock(PREFIX + "getHuluReport", 0, 30)) {
                log.info("getHuluReport start");
                handleHuluTask();
            }
        } catch (Exception e) {
            log.error("getHuluReport error" + e.getMessage());
        } finally {
            if (!getLock) {
                return;
            }
            RedissLockUtil.unlock(PREFIX + "getHuluReport");
        }
    }

    private void handleHuluTask() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        Integer size = 5;
        params.put("size", size);

        int totalPageNum = userHuluDAO.findJxlWaitReportCount();
        int total = 0;
        if (totalPageNum > 0) {
            if (totalPageNum % size > 0) {
                total = totalPageNum / size + 1;
            } else {
                total = totalPageNum / size;
            }
        }
        for (int i = 0; i < total; i++) {
            params.put("start", i*size);
            List<HashMap<String, Object>> list = userHuluDAO.findJxlWaitReport(params);
            if (CollectionUtils.isNotEmpty(list)) {
                for (final HashMap<String, Object> map : list) {
                    try {
                        ThreadPool.getInstance().run(new Runnable() {
                            @Override
                            public void run() {
                                HashMap<String, Object> map1 = new HashMap<String, Object>();
                                map1.putAll(map);
                                ServiceResult serviceResult = huLuService.findUserReport(map1);
                                if (serviceResult.isSuccessed()) {
                                    map1.put("detail", serviceResult.getMsg());
                                    UserHulu hulu = huLuService.createhl(map1);
                                    if (hulu != null) {
                                        // set jxl_detail_status=2
                                        hulu.setJxlDetailStatus(Constant.USER_AUTHENTIC);
                                        userHuluDAO.updateByUserIdSelective(hulu);
                                    } else {
                                        log.info("updatehl error hulu=" + hulu);
                                    }
                                }
                            }
                        });

                    } catch (Exception e) {
                        log.error("findHlReport error map=" + map, e);
                    }
                }
                list = null;
            } else {
                break;
            }
        }
    }

}
